/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.tnl.hunter.webchat.controller;

import com.biz.hunter.dao.CalendarDao;
import com.biz.hunter.dao.HunterDAO;
import com.biz.hunter.dao.WXUserDAO;
import com.biz.hunter.db.entity.Hunter;
import com.biz.hunter.db.entity.MyCalendar;
import com.biz.wechat.annotation.OAuthRequired;
import com.biz.wechat.util.DateUtil;
import com.mysql.jdbc.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 日历Controller
 *
 * @author Jerry
 * @version 2020-08-18
 */
@Controller
@RequestMapping(value = "/wechat/hunter/myCalendar/")
public class MyCalendarController {

    public static Logger logger = LoggerFactory.getLogger(MyCalendarController.class);

    @Autowired
    private CalendarDao calendarDao;

    @Autowired
    private WXUserDAO userDAO;

    @Autowired
    private HunterDAO hunterDAO;

    /**
     * 日历页面
     */
    @OAuthRequired
    @RequestMapping("get")
    @ResponseBody
    public Map<String, List<MyCalendar>> get(HttpServletRequest request,
                                             HttpServletResponse response, @RequestParam(required = false) String dateTime) {
        List<MyCalendar> entity = null;
        HttpSession session = request.getSession();
        // "o852Is7CAaACPsK06dWq5NUKlC-o";
        String openid = (String) session.getAttribute("OpenId");
        logger.info("OpenId is :{}", openid);

        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        entity = calendarDao.getByHunterId(hunter.getId());
        entity.parallelStream().map(s -> {
            StringBuilder sb = new StringBuilder();
            String year = s.getStarttime().substring(0, 4);
            String month = s.getStarttime().substring(5, 7);
            String day = s.getStarttime().substring(8, 10);
            if (month.startsWith("0")) {
                month = month.replace("0", "");
            }
            if (day.startsWith("0")) {
                day = day.replace("0", "");
            }
            sb.append(year).append("-").append(month).append("-").append(day);
            s.setDateKey(sb.toString());
            return s;
        }).collect(Collectors.toList());
        Map<String, List<MyCalendar>> map = entity.stream().collect(Collectors.groupingBy(MyCalendar::getDateKey));
        return map;
    }

    /**
     * 日历页面
     */
    @OAuthRequired
    @RequestMapping(value = "myCalendar.page", method = RequestMethod.GET)
    public String index( HttpServletRequest request,
                        HttpServletResponse response, Model model) {
        HttpSession session = request.getSession();
        // "o852Is7CAaACPsK06dWq5NUKlC-o"
        String openid = (String) session.getAttribute("OpenId");
        logger.info("OpenId is :{}", openid);
        if (org.springframework.util.StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        return "wechat/headhunter/hunter/myCalendar";
    }

    @OAuthRequired
    @RequestMapping(value = "calendarForm.page")
    public String calendarForm(HttpServletResponse response, Model model, @RequestParam(value = "dateTime") String dateTime, @RequestParam(required = false) String id) {
        MyCalendar myCalendar = new MyCalendar();
        if(!StringUtils.isEmptyOrWhitespaceOnly(id)){
            myCalendar = calendarDao.getById(id);
            myCalendar.setStarttime(myCalendar.getStarttime().split(" ")[1]);
            myCalendar.setEndtime(myCalendar.getEndtime().split(" ")[1]);

        }
        System.out.println(dateTime);
        model.addAttribute("dateTime", dateTime);
        model.addAttribute("myCalendar", myCalendar);
        return "wechat/headhunter/hunter/calendarForm";
    }


    @OAuthRequired
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Map saveOrUpdate(HttpServletRequest request, HttpServletResponse response, Model model, MyCalendar myCalendar) {
        HttpSession session = request.getSession();
        // "o852Is7CAaACPsK06dWq5NUKlC-o";/
        String openid =  (String) session.getAttribute("OpenId");
        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        myCalendar.setHunterId(hunter.getId());
        myCalendar.setUserid(hunter.getId() + "");
        myCalendar.setBook(0);
        String[] dateKeyArray = myCalendar.getDateKey().split("-");

        if (Integer.parseInt(dateKeyArray[1]) < 10) {
            dateKeyArray[1] = "0"+ dateKeyArray[1];
        }
        if (Integer.parseInt(dateKeyArray[2]) < 10) {
            dateKeyArray[2] = "0"+ dateKeyArray[2];
        }
        String currentDate = String.join("-", dateKeyArray);
        myCalendar.setStarttime(currentDate+ " " + myCalendar.getStarttime());
        myCalendar.setEndtime(currentDate+ " " + myCalendar.getEndtime());
        Map<String,String>  map = preCheck(myCalendar);
        if (map.get("code").equals("0") ){
            return  map;
        }
        if (StringUtils.isEmptyOrWhitespaceOnly(myCalendar.getId())) {
            // save
            myCalendar.setAllDay("0");
            myCalendar.setId(UUID.randomUUID().toString());
            calendarDao.save(myCalendar);
            map.put("msg","设置成功");
        }else{
            calendarDao.updateById(myCalendar);
            map.put("msg","修改成功");
        }


        return map;
    }

    private Map<String,String>  preCheck(MyCalendar myCalendar)  {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String,String> map = new HashMap<String,String>();
        map.put("code","1");
        Date startDate = null;
        try {
            startDate = sdf.parse(myCalendar.getStarttime());
            Date endDate = sdf.parse(myCalendar.getEndtime());
            Date currentDate = new Date();
            if (startDate.getTime() - currentDate.getTime() <= 0){
                map.put("msg","开始时间不能小于当前时间");
                map.put("code","0");
                return map;
            }

            if(startDate.getTime()- endDate.getTime() > 0){
                map.put("msg","开始时间不能大于结束时间");
                map.put("code","0");
                return map;
            }

            if(endDate.getTime() - startDate.getTime() <= 50*60*1000){
                map.put("msg","开放时间不能小于50分钟");
                map.put("code","0");
                return map;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int count = calendarDao.validateMycalendar(myCalendar);
        if (count >= 1){
            map.put("msg","时间有重叠，请重新设置");
            map.put("code","0");
        }
        return map;
    }


    /**
     * 查看，增加，编辑日历信息表单页面
     */
    @RequestMapping(value = "delete")
    public String addform(MyCalendar myCalendar, HttpServletRequest request,
                          HttpServletResponse response, Model model) {
        String date = request.getParameter("date");
        String enddate = request.getParameter("end");
        if (date.equals(enddate)) {
            enddate = "";
        }
        String display = "";
        String chk = "";
        if ("".equals(enddate)) {
            display = "style=\"display:none\"";
            enddate = date;
        } else {
            chk = "checked";
        }
        model.addAttribute("date", date);
        model.addAttribute("display", display);
        model.addAttribute("chk", chk);
        model.addAttribute("enddate", enddate);
        model.addAttribute("myCalendar", myCalendar);
        return "wechat/headhunter/hunter/myCalendarForm-add";
    }



    @ResponseBody
    @RequestMapping(value = "findList")
    protected List<MyCalendar> doPost(MyCalendar myCalendar,
                                      HttpServletRequest request, HttpServletResponse response,
                                      Model model) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String openid = "o852Is7CAaACPsK06dWq5NUKlC-o";//(String) session.getAttribute("OpenId");
        Hunter hunter = hunterDAO.getByActivateHunter(openid);

        List<MyCalendar> calendars = calendarDao.listByHunterId(hunter.getId());
        return calendars;
    }

    /**
     * 新建日历
     */
    @ResponseBody
    @RequestMapping(value = "add")
    public String add(MyCalendar myCalendar, HttpServletRequest request,
                      HttpServletResponse response, Model model) {
        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        myCalendar.setHunterId(hunter.getId());
        String title = request.getParameter("title");// 事件内容
        String isallday = request.getParameter("allDay");// 是否是全天事件
        String startDate = request.getParameter("sdate");
        String endDate = request.getParameter("edate");
        String s_time = request.getParameter("stime");
        String e_time = request.getParameter("etime");

        String start = startDate + " " + s_time;
        String end = endDate + " " + e_time;

//        if (Objects.equals(isallday, "1")) {
//            end =
//        }


        String[] colors = {"#360", "#f30", "#06c"};
        int index = (int) (Math.random() * colors.length);
        myCalendar.setId(UUID.randomUUID().toString());
        myCalendar.setTitle(title);
        myCalendar.setStarttime(start);
        myCalendar.setEndtime(end);
        myCalendar.setAllDay(isallday);
        myCalendar.setColor(colors[index]);
        myCalendar.setHunterId(hunter.getId());
        calendarDao.save(myCalendar);
//		myCalendarService.save(myCalendar);

        return "1";
    }

    /**
     * 编辑日历
     */
    @ResponseBody
    @RequestMapping(value = "edit")
    public String edit(MyCalendar myCalendar, HttpServletRequest request,
                       HttpServletResponse response, Model model) {
        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        Hunter hunter = hunterDAO.getByActivateHunter(openid);

        String events = request.getParameter("event");// 事件内容
        String isallday = request.getParameter("isallday");// 是否是全天事件
        String isend = request.getParameter("isend");// 是否有结束时间
        String startdate = request.getParameter("startdate");
        String enddate = request.getParameter("enddate");
        String s_time = request.getParameter("s_hour") + ":"
                + request.getParameter("s_minute") + ":00";
        String e_time = request.getParameter("e_hour") + ":"
                + request.getParameter("e_minute") + ":00";

        String start = "";
        String end = "";
        if ("1".equals(isallday) && "1".equals(isend)) {
            start = startdate;
            end = enddate;
        } else if ("1".equals(isallday) && isend == null) {
            start = startdate;
        } else if (isallday == null && "1".equals(isend)) {
            start = startdate + " " + s_time;
            end = enddate + " " + e_time;
            isallday = "0";
        } else {
            start = startdate + " " + s_time;
            isallday = "0";
        }

        String[] colors = {"#360", "#f30", "#06c"};
        int index = (int) (Math.random() * colors.length);
        myCalendar.setTitle(events);
        myCalendar.setStarttime(start);
        myCalendar.setEndtime(end);
        myCalendar.setAllDay(isallday);
        myCalendar.setColor(colors[index]);
        myCalendar.setHunterId(hunter.getId());
//		myCalendarService.save(myCalendar);

        model.addAttribute("myCalendar", myCalendar);

        return "1";
    }

    /**
     * 删除日历
     */
    @RequestMapping(value = "del")
    public String del(@RequestParam(required = true) String id,
                      RedirectAttributes redirectAttributes) {

        calendarDao.deleteById(id);
        return "wechat/headhunter/hunter/myCalendar";

    }

    /**
     * 縮放日歷
     */
    @ResponseBody
    @RequestMapping(value = "resize")
    public String resize(MyCalendar myCalendar, HttpServletRequest request,
                         HttpServletResponse response, Model model) {

        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        Hunter hunter = hunterDAO.getByActivateHunter(openid);

        Integer daydiff = Integer.parseInt(request.getParameter("daydiff")) * 24 * 60 * 60;
        Integer minudiff = Integer.parseInt(request.getParameter("minudiff")) * 60;
        String start = myCalendar.getStarttime();
        long lstart = DateUtil.toTimeStamp(start);
        String end = myCalendar.getEndtime();
        Integer difftime = daydiff + minudiff;

        if ("".equals(end)) {
            myCalendar.setEndtime(DateUtil.getDateTimeStr(lstart + difftime));
            myCalendar.setHunterId(hunter.getId());
//			myCalendarService.save(myCalendar);
        } else {
            long lend = DateUtil.toTimeStamp(end);
            myCalendar.setEndtime(DateUtil.getDateTimeStr(lend + difftime));
            myCalendar.setHunterId(hunter.getId());
//			myCalendarService.save(myCalendar);
        }
        return "1";
    }

    /**
     * 拖拽日历
     */
    @ResponseBody
    @RequestMapping(value = "drag")
    public String drag(MyCalendar myCalendar, HttpServletRequest request,
                       HttpServletResponse response, Model model) {


        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        Hunter hunter = hunterDAO.getByActivateHunter(openid);

        Integer daydiff = Integer.parseInt(request.getParameter("daydiff")) * 24 * 60 * 60;
        Integer minudiff = Integer.parseInt(request.getParameter("minudiff")) * 60;
        String allday = request.getParameter("allday");
        String start = myCalendar.getStarttime();
        long lstart = DateUtil.toTimeStamp(start);

        String end = myCalendar.getEndtime();
        if ("true".equals(allday)) {
            if ("".equals(end)) {
                myCalendar.setStarttime(DateUtil.getDateTimeStr(lstart + daydiff));
                myCalendar.setHunterId(hunter.getId());
//				myCalendarService.save(myCalendar);
            } else {
                long lend = DateUtil.toTimeStamp(end);
                myCalendar.setStarttime(DateUtil.getDateTimeStr(lstart + daydiff));
                myCalendar.setEndtime(DateUtil.getDateTimeStr(lend + daydiff));
                myCalendar.setHunterId(hunter.getId());
//				myCalendarService.save(myCalendar);
            }
        } else {
            Integer difftime = daydiff + minudiff;
            if ("".equals(end)) {
                myCalendar.setStarttime(DateUtil.getDateTimeStr(lstart + difftime));
                myCalendar.setHunterId(hunter.getId());
//				myCalendarService.save(myCalendar);
            } else {
                long lend = DateUtil.toTimeStamp(end);
                myCalendar.setStarttime(DateUtil.getDateTimeStr(lstart + difftime));
                myCalendar.setEndtime(DateUtil.getDateTimeStr(lend + difftime));
                myCalendar.setHunterId(hunter.getId());
//				myCalendarService.save(myCalendar);
            }
        }
        return "1";
    }

}